import { ref } from 'vue';

import { getMaterialListDrop } from '@/apis/system/config/material';
import { IMaterialDrop } from '@/apis/system/config/model/materialModel';

export const useRelation = (searchForm: any) => {
  const materialList = ref<IMaterialDrop[]>([]);
  const selectFactorNo = ref('');
  const showFactorDialog = ref(false);
  const selectOptions = ref<LabelValueOptions>([]);
  const selectOptionsOriginal = ref<LabelValueOptions>([]);
  const unitOptions = ref<string[]>([]);

  const getUnitListByFactor = (materialNo: string) => {
    searchForm.dataUnit = '';
    const materialIndex = selectOptions.value.findIndex(n => n.value == materialNo);
    searchForm.materialName = materialIndex > -1 ? selectOptions.value[materialIndex].label : '';
    const index = materialList.value.findIndex((n: IMaterialDrop) => n.materialNo == materialNo);
    if (index > -1) {
      unitOptions.value = materialList.value[index].materialUnit;
    } else {
      unitOptions.value = [];
    }
  };
  const remoteMethod = (query: string) => {
    if (query) {
      selectOptions.value = selectOptions.value.filter(item => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    } else {
      selectOptions.value = [];
    }
  };
  const loadMaterialListDrop = () => {
    return new Promise((resolve, reject) => {
      getMaterialListDrop('')
        .then(res => {
          materialList.value = res;
          const ans = res.map(item => {
            return {
              label: item.materialName,
              value: item.materialNo
            };
          });
          selectOptions.value = ans;
          resolve(ans);
        })
        .catch(() => {
          return reject();
        });
    });
  };
  const handleVisibleChange = (val: any) => {
    console.log('val', val);
    if (val && !selectOptions.value.length) {
      loadMaterialListDrop();
    }
  };
  return {
    loadMaterialListDrop,
    showFactorDialog,
    selectFactorNo,
    remoteMethod,
    handleVisibleChange,
    selectOptions,
    getUnitListByFactor,
    unitOptions
  };
};
